package lz77;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * Pääohjelma
 * 
 * @author ossi
 * 
 */
public class Cli {
	
	/**
	 * Tarkistaa onko tiedosto olemassa, ja jos se on, kysyy kirjoitetaanko
	 * tiedoston päälle.
	 * 
	 * @param filename
	 *            Tiedoston nimi
	 * @return false, jos tiedostoa ei haluta korvata, muuten true
	 */
	public static boolean checkOverWrite(String filename) {
		File f = new File(filename);
		Scanner input = new Scanner(System.in);

		if (f.exists()) {
			System.out
					.println("Warning: File " + filename + " already exists!");
			String in = "";

			while (!(in.equals("y") || in.equals("n"))) {
				System.out.print("Overwrite? (y/n)  ");
				in = input.nextLine();
			}

			return (in.equals("y"));
		}
		return true;
	}

	private static void printUsage() {
		System.out
				.println("Usage: java -jar LZ77.jar [<options>] <input file> [<output file>]");
		System.out.println("Options:");
		System.out.println("\t-d : decompress file");
		System.out
				.println("\t-b <size>: set buffer size (valid values: 2-65535, compression only)");
	}

	/**
	 * Pääohjelma
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {

		if (args.length < 1) {
			printUsage();
			return;
		}

		boolean decompress = false;
		
		
		int filearg = 0; // monesko parametri on sisääntuleva tiedosto
		char bufferSize = 65535;

		if (args[0].equals("-d")) {
			decompress = true;
			filearg = 1;
		} else if (args[0].equals("-b")) {
			filearg = 2;
			try {
				bufferSize = (char) (Integer.valueOf(args[1])).intValue();
				// String:istä char arvo
			} catch (NumberFormatException e) {
				printUsage();
				return;
			}
			
			if (bufferSize < 2){
				System.out.println("Invalid buffer size\n");
				printUsage();
				return;
			}			
		}
		
		File tmp = new File(args[filearg]);
		
		if (!tmp.exists()){
			System.out.println("File not found: "+args[filearg]);
			return;
		}

		String infile = args[filearg];
		String outfile = args[filearg] + ((decompress) ? ".dcmp" : ".lz77");

		if (args.length > filearg + 1) {
			outfile = args[filearg + 1];
		}

		if (!checkOverWrite(outfile)) {
			System.out.println("Exiting.");
			return;
		}

		if (decompress) {
			CompressedData d = FileHandler.readCompressedFile(infile);
			Lz77.decompress(d, outfile);
			System.out.println("Decompressed file saved as " + outfile);
			
			return;
		}
		
		CompressedData d = Lz77.compress(infile, bufferSize);
		FileHandler.writeCompressedFile(outfile, d);
		System.out.println("Compressed file saved as " + outfile);

	}
}
